import Phaser from 'phaser'
import { Align } from '@/config/classes/util/align'
import { Collision } from '@/config/classes/util/collision'

// eslint-disable-next-line no-unused-vars
const _w = document.getElementById('app').getBoundingClientRect().width
const _h = document.getElementById('app').getBoundingClientRect().height

export class Road extends Phaser.GameObjects.Container {
  constructor (config) {
    super(config.scene)
    this.scene = config.scene
    // 添加道路
    this.back = this.scene.add.image(0, 0, 'road')
    this.add(this.back)
    this.scene.add.existing(this)

    // this.back.displayWidth = _w / 2
    // this.back.scaleY = this.back.scaleX
    Align.scaleToGameW(this.back, 0.5)

    this.setSize(this.back.displayWidth, _h)

    // 创建路标
    this.lineGroup = this.scene.add.group()
    this.countNum = 0

    // 添加小车
    this.car = this.scene.add.sprite(-this.displayWidth / 4, _h * 0.9, 'cars')
    Align.scaleToGameW(this.car, 0.1)
    this.add(this.car)

    // 道路的点击控制小车移动
    this.back.setInteractive()
    this.back.on('pointerdown', this.changeLines, this)

    this.addObject()
  }

  addObject () {
    // 添加障碍车1
    const obj = [
      { key: 'pCar1', speed: 10, scale: 10 },
      { key: 'pCar2', speed: 10, scale: 10 },
      { key: 'cone', speed: 20, scale: 8 },
      { key: 'barrier', speed: 10, scale: 8 }
    ]
    const index = Math.floor(Math.random() * 3)
    const scale = obj[index].scale / 100
    this.object = this.scene.add.sprite(-this.displayWidth / 4, 0, obj[index].key)
    this.object.speed = obj[index].speed
    const randNum = Math.random() * 100
    if (randNum > 50) {
      this.object.x = this.displayWidth / 4
    }
    Align.scaleToGameW(this.object, scale)
    this.add(this.object)
  }

  // 点击路控制小车移动
  changeLines () {
    if (this.car.x > 0) {
      this.car.x = -this.displayWidth / 4
    } else {
      this.car.x = this.displayWidth / 4
    }
  }

  // 循环遍历创建多个路标
  makeLines () {
    this.vSpace = this.displayHeight / 10
    for (let i = 0; i < 20; i++) {
      const line = this.scene.add.image(this.x, this.vSpace * i, 'line')
      line.oy = line.y
      this.lineGroup.add(line)
    }
  }

  // 移动路标
  moveLines () {
    this.lineGroup.children.iterate(child => {
      child.y += this.vSpace / 20
    })
    this.countNum++
    if (this.countNum === 20) {
      this.countNum = 0
      this.lineGroup.children.iterate(child1 => {
        child1.y = child1.oy
      })
    }
  }

  // 移动障碍车
  moveObject () {
    this.object.y += this.vSpace / this.object.speed
    if (Collision.checkCollide(this.car, this.object) === true) {
      this.car.alpha = 0.5
    } else {
      this.car.alpha = 1
    }
    if (this.object.y > _h) {
      window._that.$emitter.emit(window._that.$G.UP_POINTS, 1)
      this.object.destroy()
      this.addObject()
    }
  }
}
